import { getAppInfo } from './index';

export const parseUser = (baseUser, orgId) => {
    // 多机构登录时判断
    const orguser = orgId ? baseUser.orgusers.find((item) => item.org_id == orgId) : baseUser.orgusers[0];

    const user = {
        // token
        token      : baseUser.token,
        // udid
        udid       : baseUser.udid,
        // user_id
        userId     : orguser.teacher.user_id,
        // user_name
        teacherName: orguser.teacher.tech_name,
        // tech_id
        teacherId  : orguser.teacher.tech_id,
        // org_id
        orgId      : orguser.org_id,
        // rlids
        rlids      : (orguser.rlids || '').split(',').filter(rild => rild !== ''),
        // 终端version
        version    : '0',
        // identity
        identity   : orguser.identity,

        orgName: orguser.organization?.org_name_cn || '',

        classGBs: []
    };

    const auth = useAuth(user);
    user.auth = auth;

    // 如果是班主任，赋值执教班
    if (auth.isClassGB()) {
        try {
            user.classGBs = orguser.identityDatas[0].mapBZR.map(thisClass => {
                return {
                    classId  : thisClass.clas_id,
                    className: thisClass.clas_name,
                    gradeId  : thisClass.grade_id,
                    gradeName: thisClass.grade_name
                };
            });
        } catch (error) {}
    }

    Object.freeze(user);
    return user;
}

export const getUser = () => {
    return getAppInfo('user');
};

export const useAuth = (user) => {
    const authMap = new Set();
    user.rlids.map(id => authMap.add(id));

    const isAuth = id => authMap.has(String(id));
    const isSystemAdmin = () => user.identity == 99;

    return {
        isAuth,
        isSystemAdmin,
        isGradeGB: () => isAuth('5'), // 小权限1：年级组长
        isClassGB: () => isAuth('4'), // 小权限2：班主任
        isExtGB: () => isAuth('45'), // 小权限3：外培人员
        isExemGB: () => isAuth('44'), // 小权限4：外聘人员
        isFnGB: () => isAuth('17'), // 小权限5：财务管理员
        isFnrGB: () => isAuth('18'), // 小权限6：财务审批员
        isAdmin: () => {
            if (isSystemAdmin()) {
                return true;
            }

            return isAuth('1') || isAuth('2') || isAuth('10') || isAuth('52');
        }
    };
};
